import React, { Component } from 'react';
import FeedbackManagementService from './feedback-management.service';
import { Button, message, Icon, Layout, Row, Col, Tabs, Spin, Modal, Input, Form, Tooltip } from 'antd';
import 'styles/feedback/feedback-detail-page.scss';
import moment from 'moment';
const { Content, Sider } = Layout;
const { TabPane } = Tabs;
const TextArea = Input.TextArea;

import maleImg from 'images/user-male.png';
import femaleImg from 'images/user-female.png';
import unknownImg from 'images/user-unknow.png';
import avatarImg from 'images/feedback-management/avatar.png';
import menuRoute from 'routes/menuRoute';
import { messages, deepCopy } from 'share/common';
import ImageUpload from 'components/image-upload';
import config from 'config';
import baseService from 'share/base.service';
import unknowImg from 'images/user-unknow.png';
import FileUpload from 'components/file-upload';

const statusMap = {
  '0': messages('basic-4.key1')/*待处理*/,
  '1': messages('basic-4.key2')/*受理中*/,
  '2': messages('basic-4.key3')/*等待回复*/,
  '3': messages('basic-4.key4')/*已解决*/,
  '99': messages('basic-4.key5')/*已关闭*/,
  '98': messages('basic-4.key6')/*已删除*/
}

class FeedbackDetailPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      showImg: false,
      replyVisible: false,
      replyLoading: false,
      operateLoading: false,
      confirmLoading: false,
      c_img_index: 0,
      data: {},
      commentSort: 'desc',
      operateSort: 'desc',
      isPersonal: false,
      replyContent: '',
      replyImgUrls: [],
      imageUploadList: [],
      replyData: [],
      historyData: [],
      avatar: unknownImg,
      currentShowImages: [],
      replyPage: {
        page: 0,
        size: 200
      },
      historyPage: {
        page: 0,
        size: 200
      }
    }
  }

  componentWillMount() {
    const { location } = this.props;
    if (location.pathname.indexOf('customer-feedback-detail-personal') !== -1) {
      this.setState({isPersonal: true})
    } else {
    }
  }

  componentDidMount() {
    this.init();
  }

  init = (id) => {
    this.setState({loading: true});
    Promise.all([
      this.getFeedbackDetail(id || this.props.params.id),
      this.getFeedBackReply(id || this.props.params.id)
    ])
      .finally(()=>{
        this.setState({loading: false});
      })
  }

  getFeedbackDetail = (id) => {
    this.setState({loading: true})
    return FeedbackManagementService.getFeedbackDetail(id || this.props.params.id)
      .then(res => {
        let data = res.data;
        this.setState({ data: res.data, loading: false });
        let params = { page: 0, size: 5, userId: data.userId };
        FeedbackManagementService.getFeedbackList(params).then((res)=>{
          if (res.status === 200) {
            this.setState({userHistory: res.data})
          }
        })
        if (res.data.userOID) {
          baseService.getUserInfo(res.data.userOID).then(res => {
            let user = res.data;
            let avatar;
            if (!user.avatar) {   //设置预览头像
              if (user.gender === 0) {
                avatar = maleImg
              } else if (user.gender === 1) {
                avatar = femaleImg
              } else {
                avatar = unknowImg
              }
            } else {
              avatar = user.avatar
            }
            this.setState({ avatar: avatar })
          })
        }
      }).catch(()=>{this.setState({loading: false})})
  };

  getFeedBackReply = (id) => {
    this.setState({replyLoading: true})
    let params = {
      feedbackId: id || this.props.params.id,
      page: this.state.replyPage.page,
      size: this.state.replyPage.size,
      sorts: [
        {
          property: "replyDatetime",
          direction: this.state.commentSort
        }
      ]
    }
    return new Promise(((resolve, reject) => {
      FeedbackManagementService.getFeedBackReply(params)
        .then((res) => {
          let result = deepCopy(res.data);
          res.data.forEach((item, index)=>{
            if (item.replyContent && item.replyContent.length) {
              let filterReply = item.replyContent.replace(/﹤/g, '<')
                .replace(/﹥/g, '>')
                .replace(/src="\/console\/script/g, 'src="https://www.sobot.com/console/script');
              result[index].replyContent = filterReply;
            }
            if (item.fileList && item.fileList.length) {
              item.fileList.forEach((singleFile, fileIndex)=>{
                result[index].fileList[fileIndex].fileURL = singleFile.fileUrl;
                result[index].fileList[fileIndex].attachmentOID = singleFile.attachmentId;
              })
            }
          })
          this.setState({replyData: result, replyLoading: false},()=>{resolve()})
        })
        .catch((res) => {
          reject()
        });
    }))
  }

  isJsonString = (str) => {
    try {
      if (typeof JSON.parse(str) == "object") {
        return true;
      }
    } catch(e) {
    }
    return false;
  }

  goToUserHistory = (id) => {
    let path = menuRoute.getPageUrlByKey(this.state.isPersonal ? 'customer-feedback-detail-personal' : 'customer-feedback-detail').replace(":id", id);
    this.context.router.push(path);
    this.init(id);
  }

  //返回
  handleBack = () => {
    if (this.state.isPersonal) {
      this.context.router.push(menuRoute.getPageUrlByKey("customer-feedback"));
    } else {
      this.context.router.push(menuRoute.getPageUrlByKey("feedback-management"));
    }
  }

  renderHistory = () => {
    const { userHistory, data } = this.state;
    return (
      <div className='history-list-box'>
        {userHistory && userHistory.length !== 0 &&
        userHistory.map((item, index)=>{
          return (
            <div className='single-box'>
              <div className="title-and-btn">
                <div className="box-title">
                  {messages('basic-4.key7')/*流水号：*/}{item.feedbackNo}
                </div>
                {
                  item.feedbackNo === data.feedbackNo ?  <div className='current'>{messages('basic-4.key8')/*当前*/}</div> :
                    <div className='detail' onClick={()=>{this.goToUserHistory(item.id)}}>{messages('common.detail')/*详情*/}</div>
                }
              </div>
              <div className='box-desc'>{messages('basic-4.key9')/*模块：*/}{item.modules && item.modules.map(item=>item.name).join('，') || '-'}</div>
              <div className='box-desc'>{messages('basic-4.key10')/*状态：*/}{statusMap[item.status] || '-'}</div>
              <div className='box-desc'>{messages('basic-4.key11')/*提交时间：*/}{moment(item.createdDate).format("YYYY-MM-DD HH:mm:ss")}</div>
              <div className='box-desc'>{messages('basic-4.key12')/*内容：*/}{item.issueContent || '-'}</div>
            </div>
          )
        })
        }
        <div className='bottom-tip'>{messages('basic-4.key13',{arg1: 5})/*最多显示{arg1}条*/}</div>
      </div>
    )
  }

  renderAllReplay = () => {
    const { replyData, replyLoading, data, avatar } = this.state;
    return (
      <Spin spinning={replyLoading}>
        <div className='comment-list-box'>
          {replyData && replyData.length !== 0 &&
          replyData.map((item)=>{
            return (
              <div className="single-comment" key={item.id}>
                <div className="avatar-img">
                  <img className='img' src={item.startType === '0' ? avatarImg : avatar}/>
                </div>
                <div className="main-content">
                  <div className="first-line">
                    <span className='user-name'>{item.startType === '0' ? item.updateUserName : data.username}</span>
                    <span className='user-type'>{item.startType === '0' ? messages('basic-4.key14')/*客服*/ : messages('basic-4.key15')/*用户*/}</span>
                    {item.replyType === '1' && <span className='tag'>{messages('basic-4.key16')/*内部可见*/}</span>}
                  </div>
                  <div className="date-line">{item.replyDatetime}</div>
                  {<div
                    className="reply-content"
                    dangerouslySetInnerHTML={{__html: item.replyContent}}
                  />}
                  {
                    <FileUpload
                      disabled
                      defaultFileList={item.fileList}
                      attachmentType="INVOICE_IMAGES"
                      isShowDefault
                      isNeedLayout
                      isShowExtraPrompt
                      showInExpenseDetail
                    />
                  }
                </div>
              </div>
            )
          })
          }
          {this.renderSortBtn('comment')}
          {!(replyData && replyData.length !== 0) &&
          <div className='no-data'>{messages('basic-4.key17')/*暂无回复数据*/}</div>
          }
        </div>
      </Spin>
    )
  }

  handleSortClick = (key, sort) => {
    if (key === 'comment') {
      this.setState({commentSort: sort === 'desc' ? 'asc' : 'desc'}, ()=>{
        this.getFeedBackReply()
      })
    }
  }

  renderSortBtn = (key) => {
    const { commentSort, operateSort, replyData, historyData } = this.state;
    const forbid = key === 'comment' ? (replyData.length === 0) : (historyData.length === 0)
    return (
      <div className={`sort-btn-box`}>
        <div
          className={`sort-btn ${key === 'comment' ? (commentSort === 'desc' ? 'active' : '') : (operateSort === 'desc' ? 'active' : '')} ${forbid ? 'forbid' : ''}`}
          onClick={()=>{!forbid && this.handleSortClick(key, key === 'comment' ? commentSort : operateSort)}}
        >
          <svg className='icon' viewBox="0 0 14 14" version="1.1" xmlns="http://www.w3.org/2000/svg" width="14" height="14">
            <path
              d="M10.932,6.5 L7,1.781 L3.067,6.5 L6,6.5 L6,14 L5,14 L4.99947919,7.49997503 L0.932479194,7.5 L7,0.218975032 L13.0675208,7.5 L8.99947919,7.49997503 L9,14 L8,14 L8,6.5 L10.932,6.5 Z"
              transform={key === 'comment' ? (commentSort === 'desc' ? 'translate(7.000000, 7.109488) scale(1, -1) translate(-7.000000, -7.109488)' : '') : (operateSort === 'desc' ? 'translate(7.000000, 7.109488) scale(1, -1) translate(-7.000000, -7.109488)' : '')}
            />
          </svg>
          {messages('basic-4.key18')/*排序*/}
        </div>
      </div>
    )
  }

  //上传图片
  handleImageUpload = (value) => {
    let replyImgUrls = [];
    value.map(item => {
      replyImgUrls.push(item.fileURL)
    });
    this.setState({
      imageUploadList: value,
      replyImgUrls
    })
  };

  //点击了回复
  handleReply = () => {
    this.setState({replyVisible: true})
  }

  handleReplyMessage = () => {
    if (this.state.replyContent.length) {
      this.setState({confirmLoading: true})
      let params = {
        feedbackId: this.state.data.id,
        replyContent: this.state.replyContent,
        fileUrls: this.state.replyImgUrls
      }
      FeedbackManagementService.sendReply(params).then((res)=>{
        if (res.status === 200) {
          message.success(messages('basic-4.key19')/*回复成功*/);
          this.setState({
            confirmLoading: false,
            replyVisible: false,
            replyContent: '',
            replyImgUrls: [],
            imageUploadList: []
          }, ()=>{
            this.init()
          })
        }
      }).catch(()=>{this.setState({confirmLoading: false})})
    } else {
      message.warn(messages('basic-4.key20')/*请输入回复内容*/)
    }
  }

  render() {
    const { data, loading, isPersonal, replyVisible, imageUploadList,
      replyContent, confirmLoading, currentShowImages } = this.state;
    const detailMap = [
      {
        name: messages('basic-4.key21')/*流水号*/,
        value: data.feedbackNo
      },
      {
        name: messages('common.column.status')/*状态*/,
        value: statusMap[data.status]
      },
      {
        name: messages('basic-4.key22')/*模块*/,
        value: data.modules && data.modules.map(item=>item.name).join('，')
      },
      {
        name: messages('common.label')/*标签*/,
        value: data.tags && data.tags.map(item=>item.name).join('，')
      },
      {
        name: messages('basic-4.key23')/*渠道*/,
        value: data.clients && data.clients.map(item=>item.name).join('，')
      },
      {
        name: messages('basic-4.key24')/*系统*/,
        value: data.platforms && data.platforms.map(item=>item.name).join('，')
      },
      {
        name: messages('basic-4.key25')/*提交时间*/,
        value: moment(data.createdDate).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        name: messages('basic-4.key26')/*更新时间*/,
        value: moment(data.lastUpdatedDate).format("YYYY-MM-DD HH:mm:ss")
      }
    ]
    return (
      <div className="feedback-list-detail">
        <Spin spinning={loading}>
          <div>
            <div className="top-btn">
              {isPersonal &&
              <Tooltip placement="top" title={(['98', '99'].indexOf(data.status) !== -1 || !(data.ticketId)) ? messages('basic-4.key27')/*已关闭状态无法回复*/ : ''}>
                <Button
                  type='primary'
                  disabled={['98', '99'].indexOf(data.status) !== -1 || !(data.ticketId)}
                  onClick={this.handleReply}
                >
                  {messages('basic-4.key28')/*回复*/}
                </Button>
              </Tooltip>
              }
              <Button onClick={this.handleBack}>{messages('common.back')/*返回*/}</Button>
            </div>

            <Layout className='content-box'>
              <Content
                style={{
                  backgroundColor: '#fff',
                  boxShadow: 'rgba(0, 0, 0, 0.1) 4px 4px 12px 0px',
                  position: 'relative',
                  overflow: 'auto',
                  height: 'calc(100vh - 107px)',
                  zIndex: 1
                }}>
                <div className="detail-box">
                  <div className="main-title">{messages('basic-4.key29')/*反馈详情*/}</div>
                  <Row gutter={[10, 12]} justify='start'>
                    {detailMap.map((item)=>{
                      return (
                        <Col md={{span: 12}} lg={{span: 12}} xxl={{span: 8}}>
                          <span className="data-title">{item.name}：</span>
                          <span className="desc">{item.value || '-'}</span>
                        </Col>
                      )
                    })}
                    <Col span={24}>
                      <span className="data-title">{messages('basic-4.key12')/*内容：*/}</span>
                      <span className="desc" dangerouslySetInnerHTML={{__html: data.issueContent && data.issueContent.replace(/﹤/g, '<')
                          .replace(/﹥/g, '>') || '-'}} />
                    </Col>
                    <Col span={24}>
                      <div className="data-title" style={{marginBottom: 8}}>{messages('basic-4.key30')/*附件：*/}</div>
                      {data.pictureUrls && data.pictureUrls.length > 0 &&
                        <FileUpload
                          disabled
                          defaultFileList={data.pictureUrls && data.pictureUrls.map((singleImg => {
                            return {
                              fileName: singleImg,
                              fileURL: singleImg,
                              attachmentOID: singleImg,
                              fileType: 'IMAGE'
                            };
                          }))}
                          attachmentType="INVOICE_IMAGES"
                          isShowDefault
                          isNeedLayout
                          isShowExtraPrompt
                          showInExpenseDetail
                        />
                      }
                      {!(data.pictureUrls && data.pictureUrls.length > 0) &&
                        <div>-</div>
                      }
                    </Col>
                  </Row>
                </div>
                <Tabs>
                  <TabPane tab={messages('basic-4.key31')/*所有回复*/} key={1}>
                    {this.renderAllReplay()}
                  </TabPane>
                </Tabs>
              </Content>
              <Sider
                width={400}
                style={{
                  backgroundColor: '#fff',
                  padding: '16px 20px',
                  overflow: 'auto',
                  height: 'calc(100vh - 107px)'
                }}>
                <div className="info-box">
                  <div className="main-title">{messages('basic-4.key32')/*用户信息*/}</div>
                  <div className='single-info'>
                    <span className='data-title'>{messages('basic-4.key33')/*姓名：*/}</span>
                    <span className="desc">{data.username || '-'}</span>
                  </div>
                  <div className='single-info'>
                    <span className='data-title'>{messages('basic-4.key34')/*联系方式：*/}</span>
                    <span className="desc">{data.mobile || '-'}</span>
                  </div>
                  <div className='single-info'>
                    <span className='data-title'>{messages('basic-4.key35')/*邮箱：*/}</span>
                    <span className="desc">{data.email || '-'}</span>
                  </div>
                  <div className='single-info'>
                    <span className='data-title'>{messages('basic-4.key36')/*租户：*/}</span>
                    <span className="desc">{data.tenantName || '-'}</span>
                  </div>
                  <div className="main-title margin-top32">{messages('basic-4.key37')/*历史反馈*/}</div>
                  {this.renderHistory()}
                </div>
              </Sider>
            </Layout>
          </div>
        </Spin>
        <Modal
          title={messages('basic-4.key28')/*回复*/}
          width={700}
          visible={replyVisible}
          onOk={this.handleReplyMessage}
          confirmLoading={confirmLoading}
          onCancel={()=>{this.setState({replyVisible: false})}}
        >
          <Form>
            <Form.Item required labelCol={{ span: 5 }} wrapperCol={{ span: 17, offset: 1 }} label={messages('basic-4.key38')/*回复内容*/}>
              <TextArea rows={3} className="issue-description-input"
                        maxLength={200}
                        value={replyContent}
                        onChange={(e)=>{this.setState({replyContent: e.target.value})}}
                        placeholder={messages('basic-4.key39')/*请输入，最多200个字符*/}/>
            </Form.Item>
            <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 17, offset: 1 }} label={messages('basic-4.key40',{arg1: 9})/*附件(最多{arg1}张)*/}>
              <div className="upload-image-notice" style={{marginBottom: 12}}>
                {messages('basic-4.key41')/*图片大小不能超过3M，且只支持jpg, jpeg, bmp, gif, png格式的图片*/}
              </div>
              <ImageUpload uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                           attachmentType="FEEDBACK_IMAGES"
                           maxNum={9}
                           fileSize={3}
                           fileType={['jpg', 'jpeg', 'bmp', 'gif', 'png']}
                           defaultFileList={imageUploadList}
                           onChange={this.handleImageUpload}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}

FeedbackDetailPage.contextTypes = {
  router: React.PropTypes.object
};

FeedbackDetailPage.propTypes = {};

export default FeedbackDetailPage;
